<?php

namespace App\Biquge;

use App\Utils\Cache;
use App\Utils\HtmlDom;
use App\Utils\Logger;

class Noval
{

    protected $url = 'http://www.biqukan.com';

    protected $prefix = 99;
    protected $limit = 999;

    protected $mpid = 0;

    protected $workers = [];
    protected $pools = [];
    const KEYS = [
        'books_1',
        'books_2',
        'books_3',
        'books_4',
        'books_5',
        'books_6',
        'books_7',
        'books_8',
    ];

    protected $queue = 'noval';

    public function getContent($url, $key)
    {
        $content = @file_get_contents($url);
        if ($content) {
            $dom = new \DOMDocument();
            @$dom->loadHTML($content);
            $dom->normalize();

            $xpath = new \DOMXPath($dom);
            $name = $xpath->query("/html//div[contains(@class,'info')]//h2")->item(0)->textContent;
            $info = $xpath->query("/html//div[contains(@class,'info')]//span");
            $options = [];
            for ($i = 0; $i < $info->length; $i++) {
                $options[] = explode('：', $info->item($i)->textContent);
            }
            $intro = $xpath->query("/html//div[contains(@class,'intro')]")->item(0)->textContent;
            $intros = explode("\n", $intro);
            $querys = $xpath->query("/html//div[contains(@class,'listmain')]//a");
            $characters = [];
            for ($i = 0; $i < $querys->length; $i++) {
                $url = $querys->item($i)->attributes->item(0)->textContent;
                $title = $querys->item($i)->textContent;
                $characters[] = compact('url', 'title');

            }
            $book = [
                'title' => $name,
                'origin_url' => $url,
                'options' => $options,
                'intro' => $intros[0] ?? '',
                'character' => $characters
            ];
            Cache::dispatch(self::KEYS[$key], $book);
            Cache::incr('success');
        } else {
            Cache::incr('fail');
            Logger::getLogger()->error("Faile => " . $url);
        }
    }

    public function getNewContent($request_url)
    {
//        $content = file_get_contents($request_url);
        $response = ioc('request')->request('get', $request_url, []);
        try {
            $content = $response->getBody()->getContents();
        } catch (\Exception $e) {
            dispatch(new NovalJob($request_url))->onQueue('noval_1');
            return;
        }
        if ($content) {
            $dom = (new HtmlDom($content));
            $metas = $dom->query('/html//meta[@property]');
            $book = [];
            for ($i = 0; $i < $metas->length; $i++) {
                $field = $value = '';
                for ($j = 0; $j < $metas[$i]->attributes->length; $j++) {
                    $attribute = $metas[$i]->attributes[$j];
                    if ($attribute->name == 'property') {
                        $arr = explode(':', $attribute->value);
                        $field = end($arr);
                    } else if ($attribute->name == 'content') {
                        $value = $attribute->value;
                    }
                }
                if ($field && $value) {
                    $book[$field] = $value;
                }
            }
            preg_match("/(\d+\_\d+.*)/", $book['latest_chapter_url'], $latest_chapter_url);
            $book['latest_chapter_url'] = $latest_chapter_url[0];
            $intro = $dom->query("/html//div[contains(@class,'intro')]")->item(0)->textContent;
            $intros = explode("\n", $intro);
            $querys = $dom->query("/html//div[contains(@class,'listmain')]//a");
            $characters = [];
            for ($i = 0; $i < $querys->length; $i++) {
                $url = $querys->item($i)->attributes->item(0)->textContent;
                $title = $querys->item($i)->textContent;
                $characters[] = compact('url', 'title');
            }
            $book['intro'] = $intros[0] ?? '';
            $book['characters'] = $characters;
            preg_match("/\d+\_\d+/", $book['url'], $id);
            $book['id'] = $id[0];
            $book['update_at'] = date('Y-m-d H:i:s');
            dispatch((new NovalSaveJob($book)))->onQueue($this->queue);
        } else {
            Logger::getLogger($this->queue)->error("error url =>" . $request_url);
        }
    }
}
